//  DualMediationMAXBannerManager.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/1/15.
//

#import "DualMediationMAXBannerManager.h"
#if __has_include(<UIKit/UIKit.h>)
#import <UIKit/UIKit.h>
#define UIKIT_AVAILABLE 1
#else
#define UIKIT_AVAILABLE 0
@class UIView;
#endif
#import "../../Utils/Logger/IMLogUtils.h"
#import "DMConfigReader.h"
#import "IMAdStrategyManager.h"
#import "DMThinkingManager.h"
#import "DMCommercialManager.h"
#import <AdjustSdk/AdjustSdk.h>
// 导入统一的DMAdDelegate协议
#import "DMAdDelegate.h"

// Firebase Analytics
#if __has_include(<FirebaseAnalytics/FirebaseAnalytics.h>)
#import <FirebaseAnalytics/FirebaseAnalytics.h>
#define FIREBASE_AVAILABLE 1
#else
#define FIREBASE_AVAILABLE 0
#endif

// Facebook SDK
#if __has_include(<FBSDKCoreKit/FBSDKCoreKit.h>)
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#define FACEBOOK_AVAILABLE 1
#else
#define FACEBOOK_AVAILABLE 0
#endif

// 只在AppLovin SDK可用时导入AppLovin相关头文件
#if __has_include(<AppLovinSDK/AppLovinSDK.h>)
#import <AppLovinSDK/AppLovinSDK.h>
#define APPLOVIN_SDK_AVAILABLE 1
#else
#define APPLOVIN_SDK_AVAILABLE 0
#endif

#if APPLOVIN_SDK_AVAILABLE
@interface DualMediationMAXBannerManager ()<MAAdViewAdDelegate,MAAdRevenueDelegate>
@property (nonatomic, strong) MAAdView *bannerAdView;
// 双广告位相关私有属性
@property (nonatomic, strong) MAAdView *primaryBannerAdView;
@property (nonatomic, strong) MAAdView *secondaryBannerAdView;
#else
@interface DualMediationMAXBannerManager ()
// 在非iOS或UIKit不可用环境下，使用 id 以避免类型未定义
#if UIKIT_AVAILABLE
@property (nonatomic, strong) UIView *bannerAdView;
// 双广告位相关私有属性
@property (nonatomic, strong) UIView *primaryBannerAdView;
@property (nonatomic, strong) UIView *secondaryBannerAdView;
#else
@property (nonatomic, strong) id bannerAdView;
// 双广告位相关私有属性
@property (nonatomic, strong) id primaryBannerAdView;
@property (nonatomic, strong) id secondaryBannerAdView;
#endif
#endif
@property (nonatomic, assign) BOOL isLoadingPrimary;
@property (nonatomic, assign) BOOL isLoadingSecondary;
@property (nonatomic, strong) NSDate *primaryAdLoadTime;
@property (nonatomic, strong) NSDate *secondaryAdLoadTime;

@property (nonatomic, assign) BOOL hasShowAd;
@property (nonatomic, assign) BOOL isReloadBanner;
@property (nonatomic, assign) BOOL isTop; // banner是否顶部
@property (nonatomic, readwrite) BOOL isUserClosed; // 用户是否主动关闭了广告
@property (nonatomic, assign) NSTimeInterval showRequestTime; // 展示请求时间戳
@property (nonatomic, strong) NSString *currentAdUnitId; // 当前使用的广告位ID
@property (nonatomic, strong) NSString *currentScene; // 当前场景

@property (nonatomic, assign) double ECPM;

@end

@implementation DualMediationMAXBannerManager

static DualMediationMAXBannerManager *_banner = nil;

+ (instancetype)sharedBannerManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _banner = [[self alloc] init];
        [_banner initializeDualAdSettings];
        [IMLogUtils info:IMLogTagSDKInit format:@"🏷️ [MAX Banner] 单例管理器创建成功"];
    });
    return _banner;
}

- (void)initializeDualAdSettings
{
    // 检查是否启用双广告位
    self.isDualAdEnabled = [DMCommercialManager isDualAdEnabledForAdType:@"banner"];
    
    if (self.isDualAdEnabled) {
        // 获取主备广告位ID
        self.currentPrimaryAdUnitId = [DMConfigReader primaryBannerAdUnitIdForMAX];
        self.currentSecondaryAdUnitId = [DMConfigReader secondaryBannerAdUnitIdForMAX];
        
        // 初始化双广告位状态
        self.isPrimaryAdLoaded = NO;
        self.isSecondaryAdLoaded = NO;
        self.primaryAdECPM = 0.0;
        self.secondaryAdECPM = 0.0;
        
        [IMLogUtils info:IMLogTagSDKInit format:@"🏷️ [MAX Banner] 双广告位模式已启用"];
        [IMLogUtils info:IMLogTagSDKInit format:@"🏷️ [MAX Banner] 主广告位ID: %@", self.currentPrimaryAdUnitId];
        [IMLogUtils info:IMLogTagSDKInit format:@"🏷️ [MAX Banner] 备广告位ID: %@", self.currentSecondaryAdUnitId];
    } else {
        // 单广告位模式
        self.currentPrimaryAdUnitId = [DMConfigReader primaryBannerAdUnitIdForMAX];
        [IMLogUtils info:IMLogTagSDKInit format:@"🏷️ [MAX Banner] 单广告位模式"];
    }
    
    // 初始化重试机制
    [self initializeRetrySettings];
}

- (void)initializeRetrySettings
{
    self.maxRetryCount = 3;
    self.retryCount = 0;
    self.totalLoadAttempts = 0;
    self.totalFailureCount = 0;
    self.isRetryPaused = NO;
    self.lastRetryTime = 0;
    self.retryTimer = nil;
}

- (void)loadBanner
{
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 🚀 开始加载横幅广告"];
    
    // 更新统计信息
    self.totalLoadAttempts++;
    
    if (self.isDualAdEnabled) {
        // 双广告位模式
        [self loadDualBannerAds];
        return;
    }
    
    // 单广告位模式（原有逻辑）
#if APPLOVIN_SDK_AVAILABLE
    [[DMConfigReader sharedInstance] loadConfig];
    NSString *adUnitId = [[DMConfigReader sharedInstance] bannerAdConfigs][1].ad_unitID;
    
    if (!adUnitId || adUnitId.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] ❌ 横幅广告单元ID为空"];
        
        // 埋点：SDK_ad_fill_fail 广告填充失败事件打点
        @try {
            NSDictionary *fillFailParams = @{
                @"w_ad_type": @"banner",
                @"w_ad_unit_id": adUnitId ?: @"",
                @"w_ad_scene": @"default",
                @"w_error_code": @"2001",
                @"w_error_msg": @"Ad unit ID is empty",
                @"w_platform": @"MAX",
                @"w_network": @"AppLovin"
            };
            [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_fail" properties:fillFailParams];
            [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点: SDK_ad_fill_fail"];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点异常: %@", exception.reason];
        }
        
        return;
    }
    
    // 埋点：SDK_ad_fill_request 广告填充请求事件打点
    @try {
        NSDictionary *fillRequestParams = @{
            @"w_ad_type": @"banner",
            @"w_ad_unit_id": adUnitId,
            @"w_ad_scene": @"default",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_request" properties:fillRequestParams];
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点: SDK_ad_fill_request"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点异常: %@", exception.reason];
    }
    
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 📱 横幅广告单元ID: %@", adUnitId];
    
    MAAdFormat *adFormat = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? [MAAdFormat leader] : [MAAdFormat banner];
    self.bannerAdView = [[MAAdView alloc] initWithAdUnitIdentifier:adUnitId adFormat:adFormat];
    self.bannerAdView.delegate = self;
    self.bannerAdView.revenueDelegate = self;
    CGFloat defaultWidth = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? 728.0 : 320.0;
    CGFloat bannerHeight = [self bannerHeightForCurrentDevice];
    self.bannerAdView.frame = CGRectMake(0, 0, defaultWidth, bannerHeight);
    self.currentAdUnitId = adUnitId;
    
    [self.bannerAdView loadAd];
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] ✅ 横幅广告加载请求已发送"];
#else
    [IMLogUtils warning:IMLogTagAd format:@"🏷️ [MAX Banner] ❌ AppLovin SDK 不可用，无法加载 Banner 广告"];
    
    // 埋点：SDK_ad_fill_fail 广告填充失败事件打点
    @try {
        NSDictionary *fillFailParams = @{
            @"w_ad_type": @"banner",
            @"w_ad_unit_id": @"",
            @"w_ad_scene": @"default",
            @"w_error_code": @"3001",
            @"w_error_msg": @"AppLovin SDK not available",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_fail" properties:fillFailParams];
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点: SDK_ad_fill_fail"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点异常: %@", exception.reason];
    }
#endif
}

- (void)showBanner
{
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [MAX Banner] 🎯 展示横幅广告"];    
    // 获取广告策略管理器
    IMAdStrategyManager *strategyManager = [IMAdStrategyManager sharedManager];
    IMAdScene scene = IMAdSceneBannerLevelEnter;
    
    // 埋点：SDK_ad_show_request 广告展示请求事件打点
    @try {
        NSDictionary *showRequestParams = @{
            @"w_ad_type": @"banner",
            @"w_ad_unit_id": @"",
            @"w_ad_scene": @"default",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        };
#if APPLOVIN_SDK_AVAILABLE
        if (self.bannerAdView && self.bannerAdView.adUnitIdentifier) {
            showRequestParams = @{
                @"w_ad_type": @"banner",
                @"w_ad_unit_id": self.bannerAdView.adUnitIdentifier,
                @"w_ad_scene": @"default",
                @"w_platform": @"MAX",
                @"w_network": @"AppLovin"
            };
        }
#endif
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_request" properties:showRequestParams];
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点: SDK_ad_show_request"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点异常: %@", exception.reason];
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [MAX Banner]   - 广告加载状态: %@", self.isLoadBanner ? @"已加载" : @"未加载"];
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [MAX Banner]   - 用户关闭状态: %@", self.isUserClosed ? @"已关闭" : @"未关闭"];
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [MAX Banner]   - 位置设置: %@", self.isTop ? @"顶部" : @"底部"];
    
#if APPLOVIN_SDK_AVAILABLE
    // 双广告位模式检查
    if (self.isDualAdEnabled) {
        // 检查是否有可用的广告位
        if (!self.isPrimaryAdLoaded && !self.isSecondaryAdLoaded) {
            [IMLogUtils warning:IMLogTagGeneral format:@"🏷️ [MAX Banner] ❌ 双广告位都未加载，无法展示"];
            return;
        }
        
        // 选择最优广告位
        NSString *optimalAdUnitId = [self selectOptimalAdUnitId];
        if ([optimalAdUnitId isEqualToString:self.currentPrimaryAdUnitId] && self.primaryBannerAdView) {
            self.bannerAdView = self.primaryBannerAdView;
            self.currentAdUnitId = self.currentPrimaryAdUnitId;
            self.ECPM = self.primaryAdECPM;
            [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [MAX Banner] 选择主广告位展示"];
        } else if ([optimalAdUnitId isEqualToString:self.currentSecondaryAdUnitId] && self.secondaryBannerAdView) {
            self.bannerAdView = self.secondaryBannerAdView;
            self.currentAdUnitId = self.currentSecondaryAdUnitId;
            self.ECPM = self.secondaryAdECPM;
            [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [MAX Banner] 选择备用广告位展示"];
        } else {
            [IMLogUtils warning:IMLogTagGeneral format:@"🏷️ [MAX Banner] ❌ 无可用的广告位视图"];
            return;
        }
    }
    
    BOOL ready = self.bannerAdView && (self.isLoadBanner || (self.isDualAdEnabled && (self.isPrimaryAdLoaded || self.isSecondaryAdLoaded)));
    if (!ready) {
        // 埋点：SDK_ad_show_fail 广告展示失败事件打点
        @try {
            NSDictionary *showFailParams = @{
                @"w_ad_type": @"banner",
                @"w_ad_unit_id": @"",
                @"w_ad_scene": @"default",
                @"w_error_code": @"4001",
                @"w_error_msg": @"Banner ad not ready or not loaded",
                @"w_platform": @"MAX",
                @"w_network": @"AppLovin"
            };
            [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
            [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点: SDK_ad_show_fail"];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点异常: %@", exception.reason];
        }
        [IMLogUtils warning:IMLogTagGeneral format:@"🏷️ [MAX Banner] ❌ 横幅广告未准备好或未加载"];
        #else
        // 非 AppLovin 环境：直接上报失败
        @try {
            NSDictionary *showFailParams = @{
                @"w_ad_type": @"banner",
                @"w_ad_unit_id": @"",
                @"w_ad_scene": @"default",
                @"w_error_code": @"3001",
                @"w_error_msg": @"AppLovin SDK not available",
                @"w_platform": @"MAX",
                @"w_network": @"AppLovin"
            };
            [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
            [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点: SDK_ad_show_fail"];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点异常: %@", exception.reason];
        }
        [IMLogUtils warning:IMLogTagGeneral format:@"🏷️ [MAX Banner] ❌ AppLovin SDK 不可用，无法展示 Banner 广告"];
        #endif
        return;
    }

#if APPLOVIN_SDK_AVAILABLE
    // 使用 UIKit 直接定位到安全区顶部/底部，并占满宽度
    UIWindow *keyWindow = nil;
    if (@available(iOS 13.0, *)) {
        for (UIWindowScene *scene in UIApplication.sharedApplication.connectedScenes) {
            if (scene.activationState == UISceneActivationStateForegroundActive) {
                for (UIWindow *w in scene.windows) {
                    if (w.isKeyWindow) { keyWindow = w; break; }
                }
                if (!keyWindow) { keyWindow = scene.windows.firstObject; }
                break;
            }
        }
    } else {
        keyWindow = UIApplication.sharedApplication.keyWindow;
    }
    if (!keyWindow && UIApplication.sharedApplication.windows.count > 0) {
        keyWindow = UIApplication.sharedApplication.windows.firstObject;
    }
    UIViewController *rootVC = keyWindow.rootViewController;
    while (rootVC.presentedViewController) { rootVC = rootVC.presentedViewController; }
    UIView *rootView = rootVC.view;

    if (rootView) {
        // 双广告位模式：确保未选中的广告视图被移除，避免顶部/底部同时存在
        if (self.isDualAdEnabled) {
            if (self.primaryBannerAdView && self.primaryBannerAdView != self.bannerAdView) {
                SEL removeSel = NSSelectorFromString(@"removeFromSuperview");
                if ([self.primaryBannerAdView respondsToSelector:removeSel]) {
                    [self.primaryBannerAdView performSelector:removeSel];
                }
            }
            if (self.secondaryBannerAdView && self.secondaryBannerAdView != self.bannerAdView) {
                SEL removeSel = NSSelectorFromString(@"removeFromSuperview");
                if ([self.secondaryBannerAdView respondsToSelector:removeSel]) {
                    [self.secondaryBannerAdView performSelector:removeSel];
                }
            }
        }

        if (self.bannerAdView.superview != rootView) {
            [self.bannerAdView removeFromSuperview];
            [rootView addSubview:self.bannerAdView];
        }

        CGSize size = rootView.bounds.size;
        UIEdgeInsets insets = UIEdgeInsetsZero;
        if (@available(iOS 11.0, *)) { insets = rootView.safeAreaInsets; }
        CGFloat height = [self bannerHeightForCurrentDevice];
        CGFloat width = size.width > 0 ? size.width : [self bannerWidthForCurrentDevice];
        CGFloat y = self.isTop ? insets.top : (size.height - insets.bottom - height);
        if (y < 0) { y = 0; }
        self.bannerAdView.frame = CGRectMake(0, y, width, height);
        self.bannerAdView.autoresizingMask = self.isTop
            ? (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin)
            : (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin);
    }

    // 尺寸校验：避免记录成功但视图不可见
    if (self.bannerAdView.frame.size.width <= 0 || self.bannerAdView.frame.size.height <= 0) {
        @try {
            NSDictionary *showFailParams = @{
                @"w_ad_type": @"banner",
                @"w_ad_unit_id": self.currentAdUnitId ?: self.bannerAdView.adUnitIdentifier ?: @"",
                @"w_ad_scene": @"default",
                @"w_error_code": @"4003",
                @"w_error_msg": @"Banner frame size is zero",
                @"w_platform": @"MAX",
                @"w_network": @"AppLovin"
            };
            [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
            [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点: SDK_ad_show_fail"];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点异常: %@", exception.reason];
        }
        return;
    }
    
    // 更新广告展示记录
    [strategyManager updateAdShowRecord:scene level:1];
    
    // 埋点：SDK_ad_show_success 广告展示成功事件打点
    @try {
        NSDictionary *showSuccessParams = @{
            @"w_ad_type": @"banner",
            @"w_ad_unit_id": self.currentAdUnitId ?: self.bannerAdView.adUnitIdentifier ?: @"",
            @"w_ad_scene": @"default",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_success" properties:showSuccessParams];
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点: SDK_ad_show_success"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点异常: %@", exception.reason];
    }
    
    // 埋点：SDK_ad_show_completed 广告播放完成事件打点 (Banner广告展示即完成)
    @try {
        NSDictionary *showCompletedParams = @{
            @"w_ad_type": @"banner",
            @"w_ad_unit_id": self.currentAdUnitId ?: self.bannerAdView.adUnitIdentifier ?: @"",
            @"w_ad_scene": @"default",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_completed" properties:showCompletedParams];
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点: SDK_ad_show_completed"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点异常: %@", exception.reason];
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [MAX Banner] ✅ 横幅广告展示成功: %@", self.currentAdUnitId ?: @"unknown"];
    
    @try {
        NSString *scene = self.currentScene ?: @"default";
        double ecpm = self.ECPM;
        NSDictionary *bannerShowParams = @{ @"w_scene": scene, @"w_revenue": @(ecpm),@"w_auctionId":[DMConfigReader auctionId] };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"AD_Banner_show" jsonStr:bannerShowParams];
        
        NSString *adUnitIdForAdjust = self.bannerAdView.adUnitIdentifier ?: @"";
        double revenueUSDForAdjust = 0.0; // 单次展示收入（USD）在show阶段不可用
        NSString *networkName = @"";
        NSString *creativeId = @"";

        if (revenueUSDForAdjust > 0.0 && adUnitIdForAdjust.length > 0) {
            ADJAdRevenue *adjustAdRevenue = [[ADJAdRevenue alloc] initWithSource:@"applovin_max_sdk"];
            [adjustAdRevenue setRevenue:revenueUSDForAdjust currency:@"USD"];
            if (networkName.length > 0) {
                [adjustAdRevenue setAdRevenueNetwork:networkName];
            }
            [adjustAdRevenue setAdRevenueUnit:adUnitIdForAdjust];
            // MAX 在 show 阶段无法可靠获取 placement，这里保持为空
            [adjustAdRevenue setAdRevenuePlacement:@""];
            [adjustAdRevenue addPartnerParameter:@"ad_format" value:@"banner"];
            [adjustAdRevenue addPartnerParameter:@"ad_unit_id" value:adUnitIdForAdjust];
            if (creativeId.length > 0) {
                [adjustAdRevenue addPartnerParameter:@"creative_id" value:creativeId];
            }
            // 标注主/备广告位来源，便于后续分析
            NSString *adSource = @"unknown";
            if (self.currentPrimaryAdUnitId && [adUnitIdForAdjust isEqualToString:self.currentPrimaryAdUnitId]) {
                adSource = @"primary";
            } else if (self.currentSecondaryAdUnitId && [adUnitIdForAdjust isEqualToString:self.currentSecondaryAdUnitId]) {
                adSource = @"secondary";
            }
            [adjustAdRevenue addPartnerParameter:@"ad_source" value:adSource];
            [Adjust trackAdRevenue:adjustAdRevenue];
        } else {
            [IMLogUtils warning:IMLogTagAd format:@"🏷️ [MAX Banner] ⚠️ Adjust 收入上报跳过: adUnitId=%@, revenue=%.6f", adUnitIdForAdjust, revenueUSDForAdjust];
        }
        
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 事件上报: AD_Banner_show, w_scene=%@, w_revenue=%.2f, adUnitId=%@", scene, ecpm, self.bannerAdView.adUnitIdentifier ?: @""];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 事件上报异常: %@", exception.reason];
    }
    
    // 通知统一代理
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didShowAd:adType:)]) {
        NSString *shownAdUnitId = self.bannerAdView.adUnitIdentifier ?: (self.currentAdUnitId ?: @"");
        [self.delegate dmAdManager:(id)self didShowAd:shownAdUnitId adType:@"banner"];
    }
#else
    // 非 AppLovin 环境在前面的 !ready 分支已处理
#endif
}

// 其他方法实现
- (void)closeBanner
{
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [MAX Banner] 🚫 用户主动关闭横幅广告"];
    self.isUserClosed = YES;
    [self hideBanner];
}

- (void)hideBanner
{
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [MAX Banner] 👻 隐藏横幅广告"];
#if APPLOVIN_SDK_AVAILABLE
    if (self.bannerAdView) {
        SEL removeFromSuperviewSel = NSSelectorFromString(@"removeFromSuperview");
        if ([self.bannerAdView respondsToSelector:removeFromSuperviewSel]) {
            [self.bannerAdView performSelector:removeFromSuperviewSel];
        }
    }
    // 避免后续 didLoad 后自动展示
    self.isUserClosed = YES;
#endif
}

- (void)resumeBanner
{
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [MAX Banner] ▶️ 恢复横幅广告"];
    self.isUserClosed = NO;
    if (self.isLoadBanner) {
        [self showBanner];
    } else {
        [self loadBanner];
    }
}

- (void)checkPendingBannerDisplay
{
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [MAX Banner] 🔍 检查待展示的横幅广告"];
    if (self.isLoadBanner && !self.isUserClosed) {
//        [self showBanner];
    }
}

- (void)setBannerDirectionWithTop:(BOOL)topDir
{
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [MAX Banner] 📍 设置横幅广告位置: %@", topDir ? @"顶部" : @"底部"];
    self.isTop = topDir;
}

- (void)destroyBanner
{
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [MAX Banner] 💥 销毁横幅广告"];
#if APPLOVIN_SDK_AVAILABLE
    if (self.isDualAdEnabled) {
        // 双广告位模式：清理主备广告位
        if (self.primaryBannerAdView) {
            SEL removeFromSuperviewSel = NSSelectorFromString(@"removeFromSuperview");
            if ([self.primaryBannerAdView respondsToSelector:removeFromSuperviewSel]) {
                [self.primaryBannerAdView performSelector:removeFromSuperviewSel];
            }
            self.primaryBannerAdView = nil;
        }
        
        if (self.secondaryBannerAdView) {
            SEL removeFromSuperviewSel = NSSelectorFromString(@"removeFromSuperview");
            if ([self.secondaryBannerAdView respondsToSelector:removeFromSuperviewSel]) {
                [self.secondaryBannerAdView performSelector:removeFromSuperviewSel];
            }
            self.secondaryBannerAdView = nil;
        }
        
        // 重置双广告位状态
        self.isPrimaryAdLoaded = NO;
        self.isSecondaryAdLoaded = NO;
        self.isLoadingPrimary = NO;
        self.isLoadingSecondary = NO;
        self.primaryAdECPM = 0.0;
        self.secondaryAdECPM = 0.0;
        self.primaryAdLoadTime = nil;
        self.secondaryAdLoadTime = nil;
        self.currentAdUnitId = nil;
        
    } else {
        // 单广告位模式
        if (self.bannerAdView) {
            SEL removeFromSuperviewSel = NSSelectorFromString(@"removeFromSuperview");
            if ([self.bannerAdView respondsToSelector:removeFromSuperviewSel]) {
                [self.bannerAdView performSelector:removeFromSuperviewSel];
            }
            self.bannerAdView = nil;
        }
    }
#endif
    
    // 重置重试状态
    [self resetRetryState];
    
    self.isLoadBanner = NO;
    self.isUserClosed = NO;
}

- (void)setBannerDelegate
{
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [MAX Banner] 开始设置横幅广告代理"];
    // 若用户已隐藏，保持静默（不加载、不展示）
    if (self.isUserClosed) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [MAX Banner] 处于隐藏状态，跳过自动加载"];
        return;
    }

    if (self.isDualAdEnabled) {
        [self loadDualBannerAds];
    } else {
        [self loadBanner];
    }
}

#pragma mark - 双广告位加载方法

- (void)loadDualBannerAds
{
    if (!self.isDualAdEnabled) {
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 双广告位未启用，回退到单广告位模式"];
        [self loadBanner];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 🚀 开始加载双广告位"];
    
    // 并行加载主备广告位
    [self loadPrimaryBannerAd];
    [self loadSecondaryBannerAd];
}

- (void)loadPrimaryBannerAd
{
    if (!self.currentPrimaryAdUnitId || self.currentPrimaryAdUnitId.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] ❌ 主广告位ID为空"];
        return;
    }
    
    if (self.isLoadingPrimary) {
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 主广告位正在加载中，跳过重复请求"];
        return;
    }
    
    self.isLoadingPrimary = YES;
    self.totalLoadAttempts++;
    
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 🚀 开始加载主广告位: %@", self.currentPrimaryAdUnitId];
    
#if APPLOVIN_SDK_AVAILABLE
    // 埋点：SDK_ad_fill_request 广告填充请求事件打点
    @try {
        NSDictionary *fillRequestParams = @{
            @"w_ad_type": @"banner",
            @"w_ad_unit_id": self.currentPrimaryAdUnitId,
            @"w_ad_scene": @"default",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin",
            @"w_ad_position": @"primary"
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_request" properties:fillRequestParams];
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点: SDK_ad_fill_request (主广告位)"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点异常: %@", exception.reason];
    }
    
    MAAdFormat *primaryFormat = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? [MAAdFormat leader] : [MAAdFormat banner];
    self.primaryBannerAdView = [[MAAdView alloc] initWithAdUnitIdentifier:self.currentPrimaryAdUnitId adFormat:primaryFormat];
    self.primaryBannerAdView.delegate = self;
    self.primaryBannerAdView.revenueDelegate = self;
    self.primaryBannerAdView.frame = CGRectMake(0, 0, (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? 728.0 : 320.0, (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? 90.0 : 50.0);
    self.primaryAdLoadTime = [NSDate date];
    
    [self.primaryBannerAdView loadAd];
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] ✅ 主广告位加载请求已发送"];
#endif
}

- (void)loadSecondaryBannerAd
{
    if (!self.currentSecondaryAdUnitId || self.currentSecondaryAdUnitId.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] ❌ 备广告位ID为空"];
        return;
    }
    
    if (self.isLoadingSecondary) {
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 备广告位正在加载中，跳过重复请求"];
        return;
    }
    
    self.isLoadingSecondary = YES;
    
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 🚀 开始加载备广告位: %@", self.currentSecondaryAdUnitId];
    
#if APPLOVIN_SDK_AVAILABLE
    // 埋点：SDK_ad_fill_request 广告填充请求事件打点
    @try {
        NSDictionary *fillRequestParams = @{
            @"w_ad_type": @"banner",
            @"w_ad_unit_id": self.currentSecondaryAdUnitId,
            @"w_ad_scene": @"default",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin",
            @"w_ad_position": @"secondary"
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_request" properties:fillRequestParams];
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点: SDK_ad_fill_request (备广告位)"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点异常: %@", exception.reason];
    }
    
    MAAdFormat *secondaryFormat = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? [MAAdFormat leader] : [MAAdFormat banner];
    self.secondaryBannerAdView = [[MAAdView alloc] initWithAdUnitIdentifier:self.currentSecondaryAdUnitId adFormat:secondaryFormat];
    self.secondaryBannerAdView.delegate = self;
    self.secondaryBannerAdView.revenueDelegate = self;
    self.secondaryBannerAdView.frame = CGRectMake(0, 0, (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? 728.0 : 320.0, (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? 90.0 : 50.0);
    self.secondaryAdLoadTime = [NSDate date];
    
    [self.secondaryBannerAdView loadAd];
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] ✅ 备广告位加载请求已发送"];
#endif
}

#pragma mark - 双广告位选择和切换逻辑

- (NSString *)selectOptimalAdUnitId
{
    if (!self.isDualAdEnabled) {
        return self.currentPrimaryAdUnitId;
    }
    
    // 如果主广告位已加载且备用广告位未加载，选择主广告位
    if (self.isPrimaryAdLoaded && !self.isSecondaryAdLoaded) {
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 选择主广告位（备用未加载）"];
        return self.currentPrimaryAdUnitId;
    }
    
    // 如果备用广告位已加载且主广告位未加载，选择备用广告位
    if (!self.isPrimaryAdLoaded && self.isSecondaryAdLoaded) {
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 选择备用广告位（主广告位未加载）"];
        return self.currentSecondaryAdUnitId;
    }
    
    // 如果两个广告位都已加载，根据ECPM选择
    if (self.isPrimaryAdLoaded && self.isSecondaryAdLoaded) {
        if (self.primaryAdECPM >= self.secondaryAdECPM) {
            [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 选择主广告位（ECPM: %.2f >= %.2f）", self.primaryAdECPM, self.secondaryAdECPM];
            return self.currentPrimaryAdUnitId;
        } else {
            [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 选择备用广告位（ECPM: %.2f > %.2f）", self.secondaryAdECPM, self.primaryAdECPM];
            return self.currentSecondaryAdUnitId;
        }
    }
    
    // 默认返回主广告位ID
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 默认选择主广告位"];
    return self.currentPrimaryAdUnitId;
}

- (void)switchToSecondaryAdIfNeeded
{
    if (!self.isDualAdEnabled) {
        return;
    }
    
    // 如果主广告位加载失败且备用广告位已就绪，切换到备用广告位
    if (!self.isPrimaryAdLoaded && self.isSecondaryAdLoaded) {
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 主广告位失败，切换到备用广告位"];
        
        // 设置当前使用的广告位为备用广告位
        self.currentAdUnitId = self.currentSecondaryAdUnitId;
        self.bannerAdView = self.secondaryBannerAdView;
        
        // 重新加载主广告位
        [self loadPrimaryBannerAd];
    }
}

#pragma mark - 重试机制

- (void)resetRetryState
{
    self.retryCount = 0;
    self.isRetryPaused = NO;
    if (self.retryTimer) {
        [self.retryTimer invalidate];
        self.retryTimer = nil;
    }
}

- (BOOL)shouldRetry
{
    if (self.isRetryPaused) {
        return NO;
    }
    
    if (self.retryCount >= self.maxRetryCount) {
        return NO;
    }
    
    // 检查失败率，如果失败率过高则暂停重试
    if (self.totalLoadAttempts > 0) {
        double failureRate = (double)self.totalFailureCount / self.totalLoadAttempts;
        if (failureRate > 0.8) { // 失败率超过80%
            [IMLogUtils warning:IMLogTagAd format:@"🏷️ [MAX Banner] 失败率过高(%.1f%%)，暂停重试", failureRate * 100];
            self.isRetryPaused = YES;
            return NO;
        }
    }
    
    return YES;
}

- (NSTimeInterval)calculateRetryDelay
{
    // 指数退避：2^retryCount 秒，最大30秒
    NSTimeInterval delay = MIN(pow(2, self.retryCount), 30);
    return delay;
}

- (void)scheduleRetryWithDelay:(NSTimeInterval)delay
{
    if (self.retryTimer) {
        [self.retryTimer invalidate];
    }
    
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 计划在%.1f秒后重试", delay];
    
    self.retryTimer = [NSTimer scheduledTimerWithTimeInterval:delay
                                                       target:self
                                                     selector:@selector(performRetry)
                                                     userInfo:nil
                                                      repeats:NO];
}

- (void)performRetry
{
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 执行重试 (第%ld次)", (long)self.retryCount + 1];
    
    self.retryCount++;
    self.lastRetryTime = [[NSDate date] timeIntervalSince1970];
    
    if (self.isDualAdEnabled) {
        [self loadDualBannerAds];
    } else {
        [self loadBanner];
    }
}

#pragma mark - MAAdViewAdDelegate

#if APPLOVIN_SDK_AVAILABLE
- (void)didLoadAd:(MAAd *)ad
{
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] ✅ 横幅广告加载成功: %@", ad.adUnitIdentifier];
    
    // 埋点：SDK_ad_fill_success 广告填充成功事件打点
    @try {
        NSDictionary *fillSuccessParams = @{
            @"w_ad_type": @"banner",
            @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
            @"w_ad_scene": @"default",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin",
            @"w_revenue": @(ad.revenue)
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_success" properties:fillSuccessParams];
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点: SDK_ad_fill_success"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点异常: %@", exception.reason];
    }
    
    if (self.isDualAdEnabled) {
        // 双广告位模式：区分主备广告位
        if ([ad.adUnitIdentifier isEqualToString:self.currentPrimaryAdUnitId]) {
            // 主广告位加载成功
            self.isPrimaryAdLoaded = YES;
            self.primaryAdECPM = ad.revenue;
            self.primaryAdLoadTime = [NSDate date];
            self.isLoadingPrimary = NO;
            
            [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 主广告位加载成功，ECPM: %.2f", ad.revenue];
            
            // 重置重试状态
            [self resetRetryState];
            
        } else if ([ad.adUnitIdentifier isEqualToString:self.currentSecondaryAdUnitId]) {
            // 备用广告位加载成功
            self.isSecondaryAdLoaded = YES;
            self.secondaryAdECPM = ad.revenue;
            self.secondaryAdLoadTime = [NSDate date];
            self.isLoadingSecondary = NO;
            
            [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 备用广告位加载成功，ECPM: %.2f", ad.revenue];
        }
        
        // 选择最优广告位
        NSString *optimalAdUnitId = [self selectOptimalAdUnitId];
        if ([optimalAdUnitId isEqualToString:self.currentPrimaryAdUnitId]) {
            self.bannerAdView = self.primaryBannerAdView;
        } else {
            self.bannerAdView = self.secondaryBannerAdView;
        }
        self.currentAdUnitId = optimalAdUnitId;
        
        // 如果有任一广告位加载成功，标记为已加载
        if (self.isPrimaryAdLoaded || self.isSecondaryAdLoaded) {
            self.isLoadBanner = YES;
        }
        
    } else {
        // 单广告位模式
        self.isLoadBanner = YES;
        [self resetRetryState];
    }
    
    // 通知统一代理
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didLoadAd:adType:)]) {
        [self.delegate dmAdManager:(id)self didLoadAd:ad.adUnitIdentifier adType:@"banner"];
    }
    
    [self checkPendingBannerDisplay];
}

- (void)didFailToLoadAd:(MAAd *)ad withError:(MAError *)error
{
    [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] ❌ 横幅广告加载失败: %@ - %@ (%ld)", ad.adUnitIdentifier, error.message, (long)error.code];
    
    // 埋点：SDK_ad_fill_fail 广告填充失败事件打点
    @try {
        NSDictionary *fillFailParams = @{
            @"w_ad_type": @"banner",
            @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
            @"w_ad_scene": @"default",
            @"w_error_code": @(error.code),
            @"w_error_msg": error.message ?: @"Unknown error",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_fail" properties:fillFailParams];
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点: SDK_ad_fill_fail"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点异常: %@", exception.reason];
    }
    
    // 更新统计信息
    self.totalFailureCount++;
    
    if (self.isDualAdEnabled) {
        // 双广告位模式：区分主备广告位失败处理
        if ([ad.adUnitIdentifier isEqualToString:self.currentPrimaryAdUnitId]) {
            // 主广告位加载失败
            self.isPrimaryAdLoaded = NO;
            self.isLoadingPrimary = NO;
            
            [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 主广告位加载失败"];
            
            // 尝试切换到备用广告位
            [self switchToSecondaryAdIfNeeded];
            
        } else if ([ad.adUnitIdentifier isEqualToString:self.currentSecondaryAdUnitId]) {
            // 备用广告位加载失败
            self.isSecondaryAdLoaded = NO;
            self.isLoadingSecondary = NO;
            
            [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 备用广告位加载失败"];
        }
        
        // 如果两个广告位都失败了，考虑重试
        if (!self.isPrimaryAdLoaded && !self.isSecondaryAdLoaded) {
            if ([self shouldRetry]) {
                NSTimeInterval delay = [self calculateRetryDelay];
                [self scheduleRetryWithDelay:delay];
                return; // 不通知代理，等待重试
            } else {
                [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 双广告位都失败，不再重试"];
            }
        }
        
    } else {
        // 单广告位模式：考虑重试
        self.isLoadBanner = NO;
        if ([self shouldRetry]) {
            NSTimeInterval delay = [self calculateRetryDelay];
            [self scheduleRetryWithDelay:delay];
            return; // 不通知代理，等待重试
        }
    }
    
    // 通知统一代理
    NSError *sdkError = [NSError errorWithDomain:@"DualMediationSDK" code:error.code userInfo:@{NSLocalizedDescriptionKey: error.message ?: @"Banner load failed"}];
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToLoadAd:adType:error:)]) {
        [self.delegate dmAdManager:(id)self didFailToLoadAd:ad.adUnitIdentifier adType:@"banner" error:sdkError];
    }
}

- (void)didClickAd:(MAAd *)ad
{
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 👆 横幅广告被点击"];
    
    // 埋点：SDK_ad_show_click 广告点击事件打点
    @try {
        NSDictionary *clickParams = @{
            @"w_ad_type": @"banner",
            @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
            @"w_ad_scene": @"default",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_click" properties:clickParams];
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点: SDK_ad_show_click"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🏷️ [MAX Banner] 事件打点异常: %@", exception.reason];
    }
    
    // 通知统一代理
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didClickAd:adType:)]) {
        [self.delegate dmAdManager:(id)self didClickAd:ad.adUnitIdentifier adType:@"banner"];
    }
}

- (void)didFailToDisplayAd:(nonnull MAAd *)ad withError:(nonnull MAError *)error { 
    
}


- (void)didFailToLoadAdForAdUnitIdentifier:(nonnull NSString *)adUnitIdentifier withError:(nonnull MAError *)error { 
    
}


- (void)didHideAd:(nonnull MAAd *)ad { 
    
}

#endif

// 新接口实现
- (void)showBannerForScene:(NSString *)sceneName {
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"🏷️ [MAX Banner] ❌ 场景名称不能为空"];
        return;
    }
    
    self.currentScene = sceneName; // 记录当前场景
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 展示场景化Banner广告 - 场景: %@", sceneName];
    [self showBanner];
}

- (void)hideBannerForScene:(NSString *)sceneName {
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"🏷️ [MAX Banner] ❌ 场景名称不能为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 隐藏场景化Banner广告 - 场景: %@", sceneName];
    [self hideBanner];
}

- (BOOL)isBannerReadyForScene:(NSString *)sceneName {
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"🏷️ [MAX Banner] ❌ 场景名称不能为空"];
        return NO;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 检查场景化Banner广告是否可用 - 场景: %@", sceneName];
    
    // 检查广告策略
    IMAdStrategyManager *strategyManager = [IMAdStrategyManager sharedManager];
    BOOL shouldShowAd = [strategyManager shouldShowAdForScene:IMAdSceneBannerLevelEnter userLevel:1 onlineTime:0];
    
    if (!shouldShowAd) {
        return NO;
    }
    
    // 检查广告是否可用
    if (self.isDualAdEnabled) {
        // 双广告位模式：检查是否有任一广告位可用
        return self.isPrimaryAdLoaded || self.isSecondaryAdLoaded;
    } else {
        // 单广告位模式
        return self.isLoadBanner;
    }
}

- (void)showBannerAd:(NSString *)sceneValue position:(BannerPosition)position enableShortScreenDetection:(BOOL)enableShortScreenDetection {
    if (!sceneValue || sceneValue.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"🏷️ [MAX Banner] ❌ 场景值不能为空"];
        return;
    }
    
    self.currentScene = sceneValue; // 记录当前场景
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 🎯 展示Banner广告 - 场景: %@", sceneValue];
    
    // 设置Banner位置
    switch (position) {
        case BannerPositionTop:
            [self setBannerDirectionWithTop:YES];
            break;
        case BannerPositionBottom:
            [self setBannerDirectionWithTop:NO];
            break;
        case BannerPositionBottomTop:
            [self setBannerDirectionWithTop:NO];
            [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] BottomTop位置暂时使用底部显示"];
            break;
    }
    
    // 短屏检测逻辑（由于UIScreen不可用，简化处理）
    if (enableShortScreenDetection) {
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 启用短屏检测（当前环境简化处理）"];
    }
    
    // 检查广告策略
    IMAdStrategyManager *strategyManager = [IMAdStrategyManager sharedManager];
    BOOL shouldShowAd = [strategyManager shouldShowAdForScene:IMAdSceneBannerLevelEnter userLevel:1 onlineTime:0];
    
    if (!shouldShowAd) {
        [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] ❌ 广告策略检查失败，不展示广告"];
        return;
    }
    
    // 调用原有的展示方法
    [self showBannerWithScene:IMAdSceneBannerLevelEnter];
}

- (void)showBannerWithScene:(IMAdScene)scene {
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 展示Banner广告 - 场景值: %lu", (unsigned long)scene];
    [self showBanner];
}

- (void)preloadBannerForScene:(NSString *)sceneName {
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"🏷️ [MAX Banner] ❌ 场景名称不能为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 预加载场景Banner广告 - 场景: %@", sceneName];
    [self loadBanner];
}

- (void)destroyBannerForScene:(NSString *)sceneName {
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"🏷️ [MAX Banner] ❌ 场景名称不能为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 销毁场景Banner广告 - 场景: %@", sceneName];
    [self destroyBanner];
}

#pragma mark - MAAdRevenueDelegate

#if APPLOVIN_SDK_AVAILABLE
- (void)didCollapseAd:(nonnull MAAd *)ad { 
    
}

- (void)didExpandAd:(nonnull MAAd *)ad { 
    
}

- (void)didPayRevenueForAd:(nonnull MAAd *)ad {
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 💸 ========== 收到 Revenue Data ==========="];
    
    if (!ad || ad.revenue <= 0) {
        [IMLogUtils warning:IMLogTagAd format:@"🏷️ [MAX Banner] ❌ Revenue data 无效或收入为空"];
        return;
    }

    double revenueUSD = ad.revenue;
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 💰 Revenue 收入详情:"];
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner]   - AdUnitId: %@", ad.adUnitIdentifier ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner]   - AdNetwork: %@", ad.networkName ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner]   - Revenue: $%.6f", revenueUSD];
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner]   - CreativeId: %@", ad.creativeIdentifier ?: @"N/A"];
    
    // 确定广告格式和广告源
    NSString *AdUnitId = ad.adUnitIdentifier ?: @"";
    NSString *ad_format = @"banner";
    NSString *adSource = @"unknown";
    
    // 判断是主广告位还是备广告位
    if ([AdUnitId isEqualToString:self.currentPrimaryAdUnitId]) {
        adSource = @"primary";
    } else if ([AdUnitId isEqualToString:self.currentSecondaryAdUnitId]) {
        adSource = @"secondary";
    }
    
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner]   - ad_format: %@", ad_format];
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner]   - ad_source: %@", adSource];
    
    // ========== DMCommercialManager 策略集成 ==========
    DMCommercialManager *commercialSDK = [DMCommercialManager sharedInstance];
    
    // 1. 记录广告位性能数据
    [commercialSDK recordAdUnitPerformance:AdUnitId
                                      ecpm:revenueUSD
                                 fillRate:1.0
                                 clickRate:0.0
                                 isSuccess:YES];
    
    // 2. ECPM比较和广告位优化（双广告位模式）- 仅限Banner广告
    if ([adSource isEqualToString:@"primary"] || [adSource isEqualToString:@"secondary"]) {
        NSString *primaryAdUnitId = [DMConfigReader primaryBannerForSDKConfigFileMAX];
        NSString *secondaryAdUnitId = [DMConfigReader secondaryBannerForSDKConfigFileMAX];
        
        if (primaryAdUnitId && secondaryAdUnitId) {
            NSString *optimalAdUnitId = [commercialSDK compareAdUnitsAndSelectOptimal:primaryAdUnitId
                                                                    secondaryAdUnitId:secondaryAdUnitId];
            [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 🎯 ECPM比较结果：最优广告位 = %@", optimalAdUnitId];
        }
    }
    
    // ========== 原有上报逻辑保持不变 ==========
    // 1. 上报 Taichi
    NSNumber *revenueMicros = @(revenueUSD * 1000);
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] Taichi 上报完成: %@ micros", revenueMicros];

#if FIREBASE_AVAILABLE
    // 2. Firebase 埋点
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"ad_platform"] = @"MAX";
    params[@"ad_format"] = ad_format;
    params[@"ad_source"] = ad.networkName ?: @"";
    params[@"ad_unit_name"] = ad.adUnitIdentifier ?: @"";
    params[@"ad_unit_source"] = adSource; // 新增：标识主/备用广告位
    params[@"value"] = @(revenueUSD);
    params[@"currency"] = @"USD";
    [FIRAnalytics logEventWithName:@"ad_impression" parameters:params];
    [FIRAnalytics logEventWithName:@"Ad_Impression_Revenue" parameters:params];
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] Firebase 埋点完成"];
#endif
    
#if FACEBOOK_AVAILABLE
    // 3. Facebook 事件上报
    NSMutableDictionary *fbParams = [NSMutableDictionary dictionary];
    fbParams[@"ad_platform"] = @"MAX";
    fbParams[@"ad_unit"] = ad.adUnitIdentifier ?: @"";
    fbParams[@"ad_format"] = ad_format;
    fbParams[@"ad_source"] = ad.networkName ?: @"";
    fbParams[@"ad_unit_name"] = ad.adUnitIdentifier ?: @"";
    fbParams[@"ad_unit_source"] = adSource;
    fbParams[@"value"] = @(revenueUSD);
    fbParams[@"currency"] = @"USD";
    [FBSDKAppEvents.shared logEvent:@"ad_impression" parameters:fbParams];
    [FBSDKAppEvents.shared logEvent:@"Ad_Impression_Revenue" parameters:fbParams];
    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] Facebook 事件上报完成"];
#endif

    // 4. 10个等级的太极打点机制
    [self reportMultiLevelTaichiRevenue:revenueUSD adFormat:ad_format adSource:adSource];

    [IMLogUtils info:IMLogTagAd format:@"🏷️ [MAX Banner] 💸 Revenue Data 处理完成"];
}
#endif

#pragma mark - 10个等级的太极打点机制

// 定义收益等级阈值（Banner广告）
// =============== 配置：10 档（0.01 ~ 0.10，每档 +0.01） ===============
static inline NSArray<NSNumber *> *WDRevenueTiers_Banner(void) {
    return @[@0.01, @0.02, @0.03, @0.04, @0.05, @0.06, @0.07, @0.08, @0.09, @0.10];
}

// 事件名与阈值一一对应，001~010 分别对应 0.01~0.10
static inline NSArray<NSString *> *WDRevenueEventNames_Banner(void) {
    return @[
        @"Total_Ads_Revenue_Banner_001", // 0.01
        @"Total_Ads_Revenue_Banner_002", // 0.02
        @"Total_Ads_Revenue_Banner_003", // 0.03
        @"Total_Ads_Revenue_Banner_004", // 0.04
        @"Total_Ads_Revenue_Banner_005", // 0.05
        @"Total_Ads_Revenue_Banner_006", // 0.06
        @"Total_Ads_Revenue_Banner_007", // 0.07
        @"Total_Ads_Revenue_Banner_008", // 0.08
        @"Total_Ads_Revenue_Banner_009", // 0.09
        @"Total_Ads_Revenue_Banner_010"  // 0.10
    ];
}

// 本地持久化键（Banner广告）
static NSString *const kWDRevenueUSDKey_Banner = @"Banner_RevenueUSD";
static NSString *const kWDLastTierKey_Banner = @"Banner_LastTier";

// 串行队列，确保线程安全
static dispatch_queue_t WDRevenueQueue_Banner(void) {
    static dispatch_queue_t queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        queue = dispatch_queue_create("com.dualmediationsdk.banner.revenue", DISPATCH_QUEUE_SERIAL);
    });
    return queue;
}

- (void)reportMultiLevelTaichiRevenue:(double)revenueUSD adFormat:(NSString *)adFormat adSource:(NSString *)adSource {
    dispatch_async(WDRevenueQueue_Banner(), ^{
        // 1) 读取当前累计收入
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        double oldTotal = [ud doubleForKey:kWDRevenueUSDKey_Banner];
        double newTotal = oldTotal + revenueUSD;
        
        [IMLogUtils info:IMLogTagAd format:@"📐 [RevTier-Banner] oldTotal=%.6f | +%.6f | newTotal=%.6f", oldTotal, revenueUSD, newTotal];
        
        // 2) 计算当前档位
        NSArray<NSNumber *> *tiers = WDRevenueTiers_Banner();
        NSInteger currentTier = -1;
        for (NSInteger i = 0; i < tiers.count; i++) {
            if (newTotal >= [tiers[i] doubleValue]) {
                currentTier = i;
            } else {
                break;
            }
        }
        
        NSInteger lastTier = -1;
        if ([ud objectForKey:kWDLastTierKey_Banner] != nil) {
            lastTier = (NSInteger)[ud integerForKey:kWDLastTierKey_Banner];
        }

        [IMLogUtils info:IMLogTagAd format:@"📐 [RevTier-Banner] lastTier=%ld | currentTier=%ld", (long)lastTier, (long)currentTier];

        // 3) 补齐新跨越的档位
        if (currentTier > lastTier) {
            NSArray<NSString *> *events = WDRevenueEventNames_Banner();
            for (NSInteger i = lastTier + 1; i <= currentTier; i++) {
                NSString *eventName = events[i];
                NSNumber *threshold = tiers[i];

                // Firebase：事件名与门槛一一对应
                NSDictionary *fa = @{
                    kFIRParameterValue: @(newTotal),         // 传累计总额（便于分析）
                    @"threshold": threshold,                // 当前门槛
                    @"ad_format": adFormat,                 // 广告格式
                    @"ad_source": adSource                  // 广告源
                };
#if FIREBASE_AVAILABLE
                [FIRAnalytics logEventWithName:eventName parameters:fa];
#endif
                
                // Facebook：同样的事件名和参数
                NSDictionary *fb = @{
                    @"value": @(newTotal),
                    @"threshold": threshold,
                    @"ad_format": adFormat,
                    @"ad_source": adSource
                };
#if FACEBOOK_AVAILABLE
                [FBSDKAppEvents.shared logEvent:eventName parameters:fb];
#endif
                
                [IMLogUtils info:IMLogTagAd format:@"📐 [RevTier-Banner] 🎯 触发里程碑: %@ (门槛=%.2f, 累计=%.6f)", eventName, [threshold doubleValue], newTotal];
            }
        }
        
        // 4) 更新本地存储
        [ud setDouble:newTotal forKey:kWDRevenueUSDKey_Banner];
        if (currentTier >= 0) {
            [ud setInteger:currentTier forKey:kWDLastTierKey_Banner];
        }
        [[NSUserDefaults standardUserDefaults] setDouble:revenueUSD forKey:@"Banner_RevenueUSD"];
        [ud synchronize];
    });
}

// 调试辅助方法：重置收益里程碑（Banner广告）
- (void)wd_resetRevenueMilestonesForDebug_Banner {
    dispatch_async(WDRevenueQueue_Banner(), ^{
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud removeObjectForKey:kWDRevenueUSDKey_Banner];
        [ud removeObjectForKey:kWDLastTierKey_Banner];
        [ud synchronize];
        [IMLogUtils info:IMLogTagAd format:@"📐 [RevTier-Banner] 🔄 已重置收益里程碑（调试用）"];
    });
}

#pragma mark - Helpers

- (CGFloat)bannerHeightForCurrentDevice
{
    return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? 90.0 : 50.0;
}

- (CGFloat)bannerWidthForCurrentDevice
{
    return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? 728.0 : 320.0;
}

#pragma mark - DMAdDelegate Registration

- (void)setAdDelegate:(id<DMAdDelegate>)delegate
{
    _delegate = delegate;
    [IMLogUtils info:IMLogTagSDKInit format:@"🏷️ [MAX Banner] DMAdDelegate 已注册"];
}

@end
